/**
 * Jaxson ajax
 *
 * Copyright Remedy Interactive, licensed under Apache version 2 license:
 *
 *  http://www.apache.org/licenses/LICENSE-2.0.html
 *
 * This notice must remain in all java source files.
 */

package org.jaxson.struts.reverseAjax;


import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.jaxson.struts.BaseAction;
import org.jaxson.struts.encoder.ResponseContentType;


/**
 * Reverse ajax implemented via polling.
 * 
 * @author Joe Maisel
 */
public class PollAction extends BaseAction
{
	private static final long serialVersionUID = 98087969879871L;
	private static final Log lager = LogFactory.getLog( PollAction.class.getName() );
	
	private boolean isSessionValid()
	{
		float expiraton = session.getMaxInactiveInterval()/60 + ((float)session.getMaxInactiveInterval()%60)/60;
		return expiraton > 1;
	}

	/**
	 * @see org.jaxson.struts.BaseAction#handle()
	 */
	@Override
	public String handle()
	{
		enableResponseType( ResponseContentType.json );
		setReturnAs( "json" );

		if( session.isNew() )
		{
			lager.debug( "new session" );
			
			ForcedReloadEvent evt = new ForcedReloadEvent();
			evt.setMessageKey( "new.session" );
			ReverseAjaxBatch batch = new ReverseAjaxBatch();
			batch.addEvent( evt );
			batch.setCommitted( true );
			setModel( batch );
			return null;
		}
		else if( !isSessionValid() )
		{
			ReverseAjaxEvent evt = new ReverseAjaxEvent();
			evt.setName( "session.expired" );
			ReverseAjaxManager.sendImmediately( session, evt );
		}

		session.setAttribute( "reverse.ajax.method", "poll" );
		ReverseAjaxBatch batch = (ReverseAjaxBatch) session.getAttribute( ReverseAjaxManager.BATCHED_SESSION_KEY );
		ReverseAjaxBatch asap = (ReverseAjaxBatch) session.getAttribute( ReverseAjaxManager.IMMEDIATE_SESSION_KEY );

		if( asap != null )
		{
			setModel( asap );
			asap.setCommitted( true );
			session.removeAttribute( ReverseAjaxManager.IMMEDIATE_SESSION_KEY );
		}
		else if( batch != null && batch.isCommitted() )
		{
			setModel( batch );
			session.setAttribute( ReverseAjaxManager.BATCHED_SESSION_KEY, new ReverseAjaxBatch() );
		}


		return null;
	}
}
